package com.atguigu.day06;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;

public class Flink03_TimeWindow_Tumbling_Watermark_Custom {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //设置默认生成WaterMark周期
        env.getConfig().setAutoWatermarkInterval(200);
        env.setParallelism(1);

        //2.从端口获取数据
        env
                .socketTextStream("localhost", 9999)
//                .readTextFile("input/sensor.txt")
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                })
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .forGenerator(new WatermarkGeneratorSupplier<WaterSensor>() {
                            @Override
                            public WatermarkGenerator<WaterSensor> createWatermarkGenerator(Context context) {
                                return new MyWaterMark(Duration.ofSeconds(3));
                            }
                        })
                        .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                            @Override
                            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                return element.getTs() * 1000;
                            }
                        }))
                .keyBy("id")
                //开启基于事件时间的滚动窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<WaterSensor, String, Tuple, TimeWindow>() {
                    @Override
                    public void process(Tuple tuple, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        String msg =
                                "窗口: [" + context.window().getStart() / 1000 + "," + context.window().getEnd() / 1000 + ") 一共有 "
                                        + elements.spliterator().estimateSize() + "条数据 ";
                        out.collect(msg);
                    }
                })
                .print();

        env.execute();
    }

    //自定义WaterMark
    public static class MyWaterMark implements  WatermarkGenerator<WaterSensor>{

        private long maxTimestamp;

        private final long outOfOrdernessMillis;

        public MyWaterMark(Duration maxOutOfOrderness) {

            this.outOfOrdernessMillis = maxOutOfOrderness.toMillis();

            // start so that our lowest watermark would be Long.MIN_VALUE.
            this.maxTimestamp = Long.MIN_VALUE + outOfOrdernessMillis + 1;
        }

        //间歇性生成WaterMark因为这个方法是间歇性调用的
        @Override
        public void onEvent(WaterSensor event, long eventTimestamp, WatermarkOutput output) {

            maxTimestamp = Math.max(maxTimestamp, eventTimestamp);
//            System.out.println("Watermark:"+(maxTimestamp-outOfOrdernessMillis-1));
//            output.emitWatermark(new Watermark(maxTimestamp-outOfOrdernessMillis-1));
        }

        //周期性生成WaterMark因为这个方法是周期性调用的
        @Override
        public void onPeriodicEmit(WatermarkOutput output) {
            System.out.println("Watermark:"+(maxTimestamp-outOfOrdernessMillis-1));
//            System.out.println("Watermark:");
            output.emitWatermark(new Watermark(maxTimestamp-outOfOrdernessMillis-1));
        }
    }
}
